# !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@File Name  : addCustomer.py
@Author     : LeeCQ
@Date-Time  : 2020/8/29 11:19

添加用户
"""
import time

from common import *
from login import login_easy, login
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import unittest

u_p = ('test', '123456')


def e(q, w):
    """交互式提示符快捷启动"""
    return AddCustomer(login_easy(*u_p), q, w)


class TestAddCustoms(unittest.TestCase):
    """"""

    def setUp(self) -> None:
        self.driver = login_easy('test', '123456')
        self.name = 'auto_02'
        self._id = 'auto_02'

    def tearDown(self) -> None:
        self.driver.close()

    def test_addCustomer(self):
        d = AddCustomer(self.driver, self.name, self._id).driver
        d.find_element_by_id('replace').click()
        time.sleep(2)
        trs = d.find_elements_by_css_selector('table#gridTable_frozen > tbody > tr')
        names = [i.find_element_by_css_selector('td:nth-child(7)').get_attribute('title') for i in trs]
        self.assertIn(self.name, names, '添加客户档案成功!')


class AddCustomer:
    iframe_tag = 'iframe402881d260d3d2e90160d4468ae00003'
    iframe_add = 'CustomerFrom2'

    def __init__(self, _driver: BaseWebDriver, name, pact_id,
                 city='西安', contact='LeeCQ', addr='陕西省汉中市南郑区',
                 detailed_addr='Auto', start='2009-8-9', end='2020-9-8',
                 company='自动化注册公司', phone_num='19011112222'
                 ):
        self.d = _driver
        self.d.implicitly_wait(8)
        self.login()  # 登录
        self.open_customer_page()  # 打开并切换到标签
        self.add_customer()  # 打开新增客户资料的页面，两次框架跳转

        self.set_company(company)  # 设置公司名
        self.set_name(name)  # 设置客户名
        self.set_pact_id(pact_id)  # 设置ID
        self.set_clearing_from()  # 结算方式
        self.set_pact_time(start, end)  # 设置时间
        self.set_city(city)  # 设置城市
        self.set_contact(contact)  # 设置联系人
        self.set_addr(addr)  # 设置发货地址
        self.set_detailed_addr(detailed_addr)  # 设置详细地址
        self.set_phone_num(phone_num)  # 设置电话号码
        self.ok()
        if __name__ == '__main__':
            time.sleep(5)

    @property
    def driver(self):
        self.d.switch_to.default_content()
        self.d.switch_to.frame(self.iframe_tag)
        return self.d

    def login(self):
        """判断登录，没登录自动登录"""
        if is_login(self.d) is False:
            self.d = login(self.d, 'test', '123456')

    def open_customer_page(self):
        """打开到标签"""
        _d = self.d
        ActionChains(_d).move_to_element(_d.find_element_by_id('402882b75ff3938e015ff396e33f0003')).perform()
        time.sleep(1)
        ActionChains(_d).move_to_element(_d.find_element_by_id('402881d260d3d2e90160d4468ae00003')).click().perform()
        _d.switch_to.frame(self.iframe_tag)
        self.d = _d
        return _d

    def add_customer(self, ):
        """"""
        self.d.find_element_by_id('customer-add').click()
        self.d.switch_to.default_content()  # 跳转到主框架
        self.d.switch_to.frame(self.iframe_add)  # 跳转到添加页面框架
        return self.d

    def set_company(self, company='自动化注册公司'):
        """设置 所属注册公司"""
        self.d.find_element_by_css_selector('#jcRegistration > div').click()
        tags = self.d.find_elements_by_css_selector('div#jcRegistration-option > '
                                                    'div.ui-select-option-content > '
                                                    'div.bbit-tree-bwrap > '
                                                    'div.bbit-tree-body > ul > li'
                                                    )
        for _t in tags:
            _t_title = _t.find_element_by_tag_name('div').get_attribute('title')
            if _t_title == company:
                _t.click()

    def set_name(self, name='AutoName'):
        """设置 客户名称"""
        self.d.find_element_by_id('name').send_keys(name)
        return self.d

    def set_pact_id(self, _id='Auto12321'):
        """设置合同ID"""
        self.d.find_element_by_id('code').send_keys(_id)
        return self.d

    def set_clearing_from(self, clearer='月结'):
        """设置结算方式"""
        self.d.find_element_by_id('settlementType').click()
        for _clear in self.d.find_elements_by_css_selector('div#settlementType-option > div > ul > li'):
            if _clear.text == clearer:
                _clear.click()
                return self.d

    def set_pact_time(self, start='2020-7-21', end='2021-06-29'):
        """设置合同开始时间"""
        # self.d.find_element_by_id('startTime').click()
        # self.d.switch_to.default_content()
        # time.sleep(1)
        # self.d.switch_to.frame(self.d.find_element_by_xpath('//iframe[@hidefocus="true"]'))
        # self._set_time(start)
        self._set_times('startTime', start)
        self._set_times('endTime', end)

    def _set_times(self, _id, _t):
        """"""
        self.d.find_element_by_id(_id).click()
        self.d.switch_to.default_content()
        time.sleep(1)
        self.d.switch_to.frame(self.d.find_element_by_xpath('//iframe[@hidefocus="true"]'))
        self._set_time(_t)

    def _set_time(self, _t: str):
        """设置时间，要求焦点已经切换到框架"""

        logger.debug('进入时间框架')
        for _ in ['/', '年', '月', '日']:
            _t = _t.replace(_, '-')
        _y, _m, _d = _t.split('-')
        logger.debug(f'{_y, _m, _d}')

        self.d.implicitly_wait(1)
        self.d.find_element_by_xpath('//*[@id="dpTitle"]/div[4]/input').send_keys(f'{Keys.BACKSPACE * 4}{_y}')
        logger.debug(f'设置年 - {_y}')
        self.d.find_element_by_xpath('//*[@id="dpTitle"]/div[3]/input').send_keys(
            f'{Keys.BACKSPACE * 2}{int(_m)}')
        self.d.execute_script("arguments[0].click();", self.d.find_element_by_xpath('//*[@id="dpTitle"]/div[2]'))
        logger.debug(f'设置月 - {_m}')

        days = [i for i in self.d.find_elements_by_css_selector('table.WdayTable > tbody > tr > td') if i.text == _d]
        day = days[0] if int(_d) < 20 else days[-1]  # 日
        ActionChains(self.d).move_to_element(day).double_click().perform()
        time.sleep(1)
        #
        try:
            self.d.find_element_by_css_selector('table.WdayTable').send_keys(Keys.ENTER)
        except:
            pass
        self.d.switch_to.default_content()
        self.d.switch_to.frame(self.iframe_add)
        self.d.implicitly_wait(6)

    def set_city(self, city='乌鲁木齐'):
        """设置城市"""
        logger.debug('设置城市')
        self.d.find_element_by_id('zone').click()
        for _clear in self.d.find_elements_by_css_selector('div#zone-option > div.bbit-tree> div > div > ul > li'):
            if city in _clear.text:
                _clear.click()
                return self.d

    def set_contact(self, contact='李老板LeeCQ'):
        """设置联系人"""
        logger.debug('设置联系人')
        self.d.find_element_by_id('contactperson').send_keys(contact)
        return self.d

    def set_addr(self, addr='陕西省汉中市南郑区'):
        """设置地址"""
        logger.debug('正在设置发货地址')
        self.d.find_element_by_id('address').send_keys(addr)
        time.sleep(1)
        self.d.find_element_by_id('address').send_keys(Keys.DOWN)
        self.d.find_element_by_id('address').send_keys(Keys.ENTER)
        return self.d

    def set_detailed_addr(self, addr='detailedAddress'):
        """设置详细地址"""
        logger.debug('设置详细地址')
        self.d.find_element_by_id('detailedAddress').send_keys(addr)

    def set_phone_num(self, num='17700001111'):
        """设置电话号码"""
        logger.debug('设置电话号码')
        self.d.find_element_by_id('iphone').send_keys(num)
        return self.d

    def ok(self):
        """确定"""
        logger.debug('焦点切换到默认框架')
        self.d.switch_to.default_content()
        time.sleep(0.5)
        # #layui-layer1 > div.layui-layer-btn > a.layui-layer-btn0
        self.d.find_element_by_css_selector('#layui-layer1 > div.layui-layer-btn > a.layui-layer-btn0').click()
        logger.info('提交客户档案成功！')


if __name__ == '__main__':
    logger.addHandler(console_handler)
    unittest.main()
    # AddCustomer(login_easy('test', '123456'), 'test_03', 'test_03')
